<?php

namespace app\common\model;

use app\admin\model\AgentAuthGroupAccess;
use think\Env;
use think\Model;
use think\Session;

class Agent extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    const STATUS_OK = 1;
    const STATUS_CLOSE = 0;


    public static function init()
    {
        self::afterInsert(function ($row) {
            AgentAuthGroupAccess::create([
                'uid' => $row['id'],
                'group_id' => 1,
            ]);

        });

        self::afterUpdate(function ($row) {

        });

    }

    public function member()
    {
        return $this->belongsTo('member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function amapProvince()
    {
        return $this->belongsTo('amap', 'province', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function amapCity()
    {
        return $this->belongsTo('amap', 'city', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function amapDistricts()
    {
        return $this->belongsTo('amap', 'districts', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function setAvatarAttr($value)
    {
        if (!empty($value)){
            $arr = parse_url($value);
            return $arr['path'];
        }
        return '';
    }

    public function getAvatarAttr($value) {
        return $value ? $value : Env::get('app.app_host')."/uploads/head/default.png";
    }



    /**
     * 重置用户密码
     * @author baiyouwen
     */
    public function resetPassword($uid, $NewPassword)
    {
        $passwd = $this->encryptPassword($NewPassword);
        $ret = $this->where(['id' => $uid])->update(['password' => $passwd]);
        return $ret;
    }

    // 密码加密
    protected function encryptPassword($password, $salt = '', $encrypt = 'md5')
    {
        return $encrypt($password . $salt);
    }

    public static function genSalt()
    {
        $str = md5(time());
        return substr($str,5);
    }

}
